<?php

namespace app\models;


use app\tools\Tool;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use Faker\Provider\Uuid;


/**
 * This is the model class for table "user_login".
 *
 * @property int $id
 * @property int $user_id 用户id
 * @property int $ip ip
 * @property string $device 设备号
 * @property string $token token
 * @property int $created_at
 */
class UserLogin extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_login';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'ip', 'created_at'], 'integer'],
            [['device'], 'safe'],
            [['token'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => '用户id',
            'ip' => 'ip',
            'device' => '设备号',
            'token' => 'token',
            'created_at' => 'Created At',
        ];
    }

    public static function generateToken(){
        $login = new UserLogin();
        $login->token = Uuid::uuid();
        $login->ip = ip2long(Yii::$app->request->userIP);
        $login->device = Yii::$app->request->userAgent;
        if(!$login->save()){
            Tool::log($login->errors);
        }
        return $login->token;
    }

    public function showIp(){
        return long2ip($this->ip);
    }

    public function getUser(){
        return $this->hasOne(Admin::class, ['id'=>'user_id']);
    }

    public static function getBearToken(){
        $authHeader = Yii::$app->getRequest()->getHeaders()->get('Authorization');
        if (preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
            return $matches[1];
        } else {
            return null;
        }
    }

    public static function getLastLogin($user_id){
        $obj = self::find()->where(['user_id' => $user_id])->orderBY("created_at desc")->one();
        return date("Y-m-d", $obj->created_at);
    }
}
